package tmt.usercenter.web.configure.security.bean;

import com.tmt.fileservice.FileSaveMode;
import com.tmt.fileservice.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tmt.usercenter.web.Application;
import tmt.usercenter.web.domain.TmtUser;
import tmt.usercenter.web.domain.security.UserDetailsImpl;
import tmt.usercenter.web.service.LoginAttemptService;
import tmt.usercenter.web.service.TmtUserService;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

@Service
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TmtUserService userService;

    @Autowired
    private IFileService fileService;

    @Autowired
    private LoginAttemptService loginAttemptService;

    @Autowired
    private HttpServletRequest request;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (loginAttemptService.isBlocked(username)) {
            throw new RuntimeException("user.login.blocked");
        }

        int count = loginAttemptService.getAllowedLoginCount(username);
        request.getSession().setAttribute(LoginAttemptService.ALLOWED_LOGIN_ATTEMPT_COUNT, count);

        int minutes = loginAttemptService.getMinutesForMaxAllowedLoginCount();
        request.getSession().setAttribute(LoginAttemptService.MINUTES_FOR_ALLOWED_LOGIN_ATTEMPT_COUNT, minutes);

        TmtUser tmtUser = null;
        tmtUser = userService.findByUsername(username);
        if (tmtUser == null) {
            throw new UsernameNotFoundException("user.login.usernameNotFound");
        }

        //此处仅获取用户在用户中心系统中的权限。
        UserDetailsImpl details = userService.getUserDetailsImpl(tmtUser, Application.SYSTEM_ID);

        try {
            //配置头像的全访问路径。
            String url = fileService.getFileDispatcher().getFileUrl(tmtUser, "avatar", FileSaveMode.PERSIST);
            details.setAvatar(url);
        } catch (Exception ignored) {
        }

        return details;
    }

    private boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[\\d]*$");
        return pattern.matcher(str).matches();
    }

}
